package com.ww.gss.exceptionhandler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.avalon.framework.parameters.ParameterException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.ww.gss.exceptions.AuthenException;
import com.ww.gss.exceptions.BusinessException;
import com.ww.gss.util.GSSWebUtil;
import com.ww.gss.util.SystemConstans;

public class GSSSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception ex) {
        logger.info("GSSSimpleMappingExceptionResolver resolveException =>" + ex);
        ex.printStackTrace();
        Map<String, Object> model = new HashMap<String, Object>();
        // 根据不同错误转向不同页面
        if (GSSWebUtil.isAjax(request)) {
            String errormsg = SystemConstans.SYSTEM_ERROR;
            String errorcode = SystemConstans.RESPONSE_LABEL_ERROR;
            if (ex instanceof BusinessException) {
                errormsg = SystemConstans.SYSTEM_ERROR;
                errorcode = SystemConstans.RESPONSE_LABEL_ERROR;
            } else if (ex instanceof ParameterException) {
                errormsg = SystemConstans.SYSTEM_ERROR;
                errorcode = SystemConstans.RESPONSE_LABEL_ERROR;
            } else if (ex instanceof AuthenException) {
                errormsg = "user or password not correct";
                errorcode = SystemConstans.RESPONSE_LABEL_APPLICATION_ERROR;
            } else {
                errormsg = "system error";
                errorcode = SystemConstans.RESPONSE_LABEL_ERROR;
            }

            logger.info("GSSSimpleMappingExceptionResolver => This is a Ajax Request");
            Map map = GSSWebUtil.buildResponseMap(errorcode, null, errormsg);
            return new ModelAndView("error", map);
        } else {
            logger.info("GSSSimpleMappingExceptionResolver => This is a Normal Request");
            model.put("ex", ex);
            // if (ex instanceof BusinessException) {
            // return new ModelAndView("error-business", model);
            // } else if (ex instanceof ParameterException) {
            // return new ModelAndView("error-parameter", model);
            // } else {
            // return new ModelAndView("error", model);
            // }
            return new ModelAndView("error", model);
        }
        // return super.resolveException(arg0, arg1, arg2, arg3);
    }
}
